package handler;

import com.alibaba.fastjson.JSONObject;
import config.CommonConfig;
import constants.DecoderConstant;
import constants.HeartBeatConstant;
import entity.MsgModel;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.AttributeKey;
import io.netty.util.CharsetUtil;

import java.util.logging.Logger;

/**
 * @description:
 * @author: sali
 * @date: 2025/2/16 下午2:06.
 * @version: 1.0
 */
public class ServerHandler extends ChannelInboundHandlerAdapter {

    private final Logger log = Logger.getLogger(ServerHandler.class.getName());

    // 定义一个 AttributeKey 用于存储编号
    private static final AttributeKey<Long> DATA_ID = AttributeKey.valueOf("data_id");

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        String s = msg.toString().trim();
        int i = s.indexOf("{");
        if (i > -1) {
            s = s.substring(i);
        }
        MsgModel msgModel;
        try {
            msgModel = JSONObject.parseObject(s, MsgModel.class);
        } catch (Exception e) {
            log.info("the format of the received agent message is invalid, msg: " + msg);
            return;
        }
        System.out.println("Received data: " + msgModel.toString());

        Long dataId = ctx.channel().attr(DATA_ID).get();
        if(dataId == null){
            log.info("channelActive, data Id:" + msgModel.getDataId());
            ctx.channel().attr(DATA_ID).set(dataId);
        }

        //响应客户端心跳
        ByteBuf buf = getByteBuf(HeartBeatConstant.SEND_SUCCESS);
        ctx.writeAndFlush(buf);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) {
        Long uniqueId = ctx.channel().attr(DATA_ID).get();
        log.info("channelInactive, data Id: " + uniqueId);
        log.info("channelInactive");
    }


    /**
     * channelReadComplete()—通知ChannelInboundHandler最后一次对channelRead()的调用是当前批量读取中的最后一条消息；
     *
     * @param ctx ctx
     */
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
        // 将未决消息冲刷到远程节点，并且关闭该 Channel
        // ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).channel().close();
        ctx.flush();
        Boolean aBoolean = CommonConfig.clientMessageList.get(ctx.channel().id());
        if (aBoolean != null) {
            CommonConfig.clientMessageList.remove(ctx.channel().id());
            ctx.close();
        } else {
            ctx.read();
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.info("server error: " + cause);
        Boolean aBoolean = CommonConfig.clientMessageList.get(ctx.channel().id());
        if (aBoolean != null) {
            CommonConfig.clientMessageList.remove(ctx.channel().id());
        }
        ctx.close();
    }

    private ByteBuf getByteBuf(String str) {
        str = str + DecoderConstant.DELIMITER;
        ByteBuf buf = Unpooled.buffer(str.getBytes(CharsetUtil.UTF_8).length);
        buf.writeBytes(str.getBytes(CharsetUtil.UTF_8));
        return buf;
    }

}
